<script setup lang="ts">
import { ElMessage, ElMessageBoxOptions, ElMessageBox, ElLoading } from 'element-plus';
import clientHelper from '../../services/clientHelper';
import { computed, onMounted, ref } from 'vue';
import { useClient } from '../../constants/client';
import { RouteConfig, RouteConfigClient, RouteConfigSummaryViewModel, RouteMatch } from '../../services/client';
import { Plus, Search } from '@element-plus/icons-vue';
import RouteEditor from './RouteEditor.vue';

const errorHandler = clientHelper.useRequestExceptionHandler(ElMessage, (opts: ElMessageBoxOptions) => {
    ElMessageBox(opts);
})
const routeConfigClient = useClient(RouteConfigClient);
const routeConfigs = ref<RouteConfigSummaryViewModel[]>([])
const editorDrawer = ref<boolean>(false)
const editingRouteConfig = ref<RouteConfig>(new RouteConfig());
const isCreateNewConfig = ref(false);

const editorTitle = computed(() => {
    return isCreateNewConfig.value ? '新增' : '编辑'
})

const load = () => {
    return routeConfigClient.listAll();
}

const clearEditingRouteConfig = () => {
    editingRouteConfig.value = new RouteConfig();
    editingRouteConfig.value.match = new RouteMatch();
    editingRouteConfig.value.match.queryParameters = [];
    editingRouteConfig.value.match.headers = []
}

const create = () => {
    editorDrawer.value = true;
    isCreateNewConfig.value = true;
    clearEditingRouteConfig();
}

const deleteConfig = (routeId: string) => {
    const loading = ElLoading.service();
    routeConfigClient.delete(routeId)
        .then(result => {
            if (result.succeeded) {
                ElMessage.success({
                    message: '删除成功！'
                })
            }
        })
        .then(refershList)
        .catch(errorHandler)
        .finally(() => {
            loading.close();
        })
}

const edit = (data: RouteConfigSummaryViewModel) => {
    const loading = ElLoading.service();
    routeConfigClient.detail(data.routeId)
        .then(routeConfig => {
            editingRouteConfig.value = routeConfig;
            isCreateNewConfig.value = false;
            editorDrawer.value = true;
        })
        .catch(errorHandler)
        .finally(() => {
            loading.close()
        });
}

const refershList = () => {
    const loading = ElLoading.service();
    return load().then(datas => {
        routeConfigs.value = [...datas]
    }).catch(errorHandler).finally(() => {
        loading.close()
    })
}

const closeEditor = () => {
    editorDrawer.value = false;
}

const handleClosed = () => {
    isCreateNewConfig.value = false;
    clearEditingRouteConfig();
}

const save = (data: RouteConfig) => {
    const loading = ElLoading.service();
    const task = isCreateNewConfig.value ? routeConfigClient.create(data) : routeConfigClient.save(data);
    task
        .then(result => {
            if (result.succeeded) {
                ElMessage.success({
                    message: '保存成功！'
                })

                closeEditor();
                refershList();
            }
            else {
                throw result;
            }
        })
        .catch(errorHandler)
        .finally(() => {
            loading.close();
        })
}

const cancel = () => {
    closeEditor()
}

onMounted(() => {
    const loading = ElLoading.service()
    load().then(datas => {
        routeConfigs.value = [...datas]
    })
        .catch(errorHandler)
        .finally(() => {
            loading.close();
        })
})
</script>
<template>
    <ElRow>
        <ElCol>
            <ElSpace>
                <ElButton type="primary" @click="refershList">
                    <ElIcon>
                        <Search />
                    </ElIcon>查询
                </ElButton>
                <ElButton @click="create">
                    <ElIcon>
                        <Plus />
                    </ElIcon>
                    新增
                </ElButton>
            </ElSpace>
        </ElCol>
    </ElRow>
    <ElRow>
        <ElCol>
            <ElTable :data="routeConfigs">
                <ElTableColumn prop="routeId" label="Route Id"></ElTableColumn>
                <ElTableColumn prop="order" label="Order"></ElTableColumn>
                <ElTableColumn prop="clusterId" label="Cluster Id"></ElTableColumn>
                <!-- <ElTableColumn prop="authorizationPolicy" label="Authorization Policy"></ElTableColumn>
                <ElTableColumn prop="rateLimiterPolicy" label="Rate Limiter Policy"></ElTableColumn>
                <ElTableColumn prop="outputCachePolicy" label="Output Cache Policy"></ElTableColumn>
                <ElTableColumn prop="timeoutPolicy" label="Timeout Policy"></ElTableColumn>
                <ElTableColumn prop="timeout" label="Timeout"></ElTableColumn>
                <ElTableColumn prop="corsPolicy" label="Cors Policy"></ElTableColumn>
                <ElTableColumn prop="maxRequestBodySize" label="Max Request Body Size"></ElTableColumn> -->
                <ElTableColumn prop="creationTime" label="Creation Time">
                    <template #default="scope: { row: RouteConfigSummaryViewModel }">
                        <span v-timeformat="scope.row.creationTime"></span>
                    </template>
                </ElTableColumn>
                <ElTableColumn prop="lastModifiedTime" label="Last Modified Time">
                    <template #default="scope: { row: RouteConfigSummaryViewModel }">
                        <span v-timeformat="scope.row.lastModifiedTime"></span>
                    </template>
                </ElTableColumn>
                <ElTableColumn prop="operations" label="操作">
                    <template #default="scope: { row: RouteConfigSummaryViewModel }">
                        <ElButton @click="edit(scope.row)">
                            <el-icon>
                                <EditPen />
                            </el-icon>
                        </ElButton>
                        <ElButton type="danger" @click="deleteConfig(scope.row.routeId!)">
                            <ElIcon>
                                <Delete />
                            </ElIcon>
                        </ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
            <ElDrawer v-model="editorDrawer" :title="editorTitle" size="80%" @closed="handleClosed"
                :destroy-on-close="true">
                <RouteEditor :data="editingRouteConfig" :is-create="isCreateNewConfig" @save="save" @cancel="cancel"></RouteEditor>
            </ElDrawer>
        </ElCol>
    </ElRow>
</template>